Protected Routes
In this article, we will continue discussing about Routing.
In our last article, we have discussed about Programmatic navigation in React.
If we look at the Output of our routing Program we have developed in the last session, we have three components named login, home and editprofile. When we enter the valid credentials we are navigating users to home component. But our application is having an issue. home or edit profile components can still be accessed by Users who don’t have the LogIn Credentials.
In this article, we will discuss about how to Protect our routes so that only Logged In Users can access Home or Edit Profile Components.
Lets Open index.js file from our demo project.
When user clicks on home link or edit profile, we have to verify if user is already logged in or not. If user is logged in, we will allow user to navigate else we will redirect user to Login Component.
Lets create one object which will manage the user authentication related part.
We will create one property isLoggedIn using which we will track if the User is logged in or not and we will initialize it to false.
Lets add a method called as onAuthenticate and with in this method, we will set isLoggedIn to true.
Lets create another method from which we will return isLoggedIn value.
We will be creating a component called SecuredRoute which would accept the component to which application has to route if the user is authenticated. Otherwise user will be redirected to login component.
We use Render Properties, we will check if user is logged in or not. If user is Logged in , we will render that respective component else we will redirect to login Component.
Now lets go to App Component, lets secure our home component and edit profile component by using our securedroute component.
Save the changes, navigate to the browser.
Now try to access home or edit profile components, we will not be able to access them.
Now enter valid credentials, we will be redirected to home component. From there we can access edit profile component.
import React, { useState, Component } from 'react';
import ReactDOM from 'react-dom';
import {BrowserRouter, Link, NavLink, Switch, Route, Redirect} from 'react-router-dom';
const authentication={
isLoggedIn:false,
onAuthentication(){
this.isLoggedIn=true;
},
getLogInStatus(){
return this.isLoggedIn;
}
}
function SecuredRoute(props){
return(
<Route path={props.path} render={data=>authentication.getLogInStatus()?(
<props.component {...data}></props.component>):
(<Redirect to={{pathname:'/'}}></Redirect>)}></Route>
)
}
function LogIn(props){
const [loginData,setLoginData]=useState({username:'',password:''});
function changeLogInData(e){
setLoginData({...loginData,[e.target.name]:e.target.value});
}
function onLogIn(){
fetch("https://localhost:44306/api/Test",{
method:'POST',
headers:{'Content-type':'application/json'},
body:JSON.stringify(loginData)
}).then(r=>r.json()).then(result=>{
if(result){
authentication.onAuthentication();
props.history.push('/home');
}
else{
alert('Invalid UserName or PassWord');
}
});
}
return(
<div>
<h2>Welcome to LogIn...</h2>
<p>
<label>UserName : <input type="text" value={loginData.username}
name="username" onChange={changeLogInData}></input></label>
</p>
<p>
<label>PassWord : <input type="text" value={loginData.password}
name="password" onChange={changeLogInData}></input></label>
</p>
<button onClick={onLogIn}>LogIn</button>
</div>
)
}
function Home(props){
function onNext(){
props.history.replace('/editprofile');
}
return(
<div>
<h2>Welcome to Home...</h2>
<button onClick={onNext}>Next</button>
</div>
);
}
function EditProfile(){
return(
<div>
<h2>Welcome to Edit Profile...</h2>
</div>
);
}
function App(){
return(
<div>
<h2>Welcome to App Component...</h2>
<Link to="/">LogIn</Link>
<NavLink to="/home" activeClassName="testClass">Home</NavLink>
<NavLink to="/editprofile" activeClassName="testClass">Edit Profile</NavLink>
<Switch>
<Route exact path="/" component={LogIn}></Route>
<SecuredRoute path="/home" component={Home}></SecuredRoute>
<SecuredRoute path="/editprofile" component={EditProfile}></SecuredRoute>
</Switch>
</div>
)
}
ReactDOM.render(<BrowserRouter><App></App></BrowserRouter>,
document.getElementById("root"));
© 2020 Pragimtech. All Rights Reserved.